package com.cyy.demo.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Data
@EnableAsync
@Configuration
@ConfigurationProperties(prefix = "thread.pool")
public class ExecutorConfig {

    private int corePoolSize;

    private int maxPoolSize;

    private int keepAliveSeconds;

    private int queueCapacity;

    private String threadNamePrefix;

    private int rejected;

    @Bean
    public Executor asyncServiceExecutor(){
        log.info("start asyncServiceExecutor ...");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);

        executor.setKeepAliveSeconds(keepAliveSeconds);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行

        RejectedExecutionHandler rejectedExecutionHandler = null;
        switch (rejected){
            //抛异常
            case 2:rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy(); //调用者线程执行
                break;
            case 3:rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy ();//抛弃队列头的任务，然后重试execute
                break;
            case 4:rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy ();//直接丢弃
                break;
            case 1:
            default:rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();//默认
        }

        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        log.info("asyncServiceExecutor init success >>>>>");
        return executor;

    }

}
